package com.sfang.common.util.download;

import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

public class DownloadUtils {

    private  static Logger LOGGER = LoggerFactory.getLogger(DownloadUtils.class);

    /**
     *
     * @param beanParams 数据源
     * @param tplPath 模板路径
     * @param response
     * @param fileName  文件名
     */
    public static void exportExcel(Map<String, Object> beanParams, String tplPath, HttpServletResponse response,String fileName) {

        try {
            response.setContentType("application/vnd..ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(( fileName+".xlsx").getBytes(), "iso-8859-1"));
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("文件名异常 [%s]", e);
        }

        XLSTransformer former = new XLSTransformer();
        InputStream in = null;
        ServletOutputStream out = null;

        try {
            in = new BufferedInputStream(new FileInputStream(tplPath));
            Workbook workbook = former.transformXLS(in, beanParams);
            out = response.getOutputStream();
            workbook.write(out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    LOGGER.error("流关闭异常 [%s]", e);
                }
            }

            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    LOGGER.error("流关闭异常 [%s]", e);
                }
            }

        }

    }
}
